package com.free.bsf.health.memoryParse;

import com.free.bsf.core.util.PropertyUtils;
import com.free.bsf.core.util.WebUtils;
import com.free.bsf.health.config.HealthProperties;
import lombok.val;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Classname ReqeustHashMap
 * @Description 请求统计
 * @Date 2021/6/7 14:18
 * @Created by chejiangyi
 */
public class RequestHashMap {
    private final String TotalEntity="bsf-total-entity";
    public void put(ObjParser.ObjInfo objInfo){
        if (!PropertyUtils.getPropertyCache(HealthProperties.BsfHealthMemoryParseRequestEnabled, true)) {
            return;
        }
        if (WebUtils.getRequest() != null) {
            val totalEntity = WebUtils.getRequest().getAttribute(TotalEntity);
            if (totalEntity != null) {
                Long count = (Long) totalEntity;
                count = count + objInfo.getObjs().size();
                WebUtils.getRequest().setAttribute(TotalEntity, count);
            } else {
                Long count = new Long(objInfo.getObjs().size());
                WebUtils.getRequest().setAttribute(TotalEntity, count);
            }
        }
    }
    public Map<String,Long> getReport(){
        Map<String,Long> rs = new HashMap<>();
       for(val thread: Thread.getAllStackTraces().keySet()){
           val webContext = WebUtils.getThreadLocalMap(thread).values().stream().filter(c->c!=null&&c instanceof WebUtils.WebContext).findFirst();
           if(webContext.isPresent()) {
               WebUtils.WebContext context=(WebUtils.WebContext)webContext.get();
               HttpServletRequest request=context.getRequest();
               if(request!=null&&request.getAttribute(TotalEntity)!=null) {
                   rs.put(request.getRequestURI(),(Long) request.getAttribute(TotalEntity));
               }
           }
       }
       return rs;
    }
}
